package com.beamfield.controller.api.mb;

import com.alibaba.fastjson.JSONObject;
import com.beamfield.common.*;
import com.beamfield.controller.common.BaseController;
import com.beamfield.controller.common.MbBaseController;
import com.beamfield.enums.HttpResultEnum;
import com.beamfield.model.AdminInfo;
import com.beamfield.model.BeamField;
import com.beamfield.modelVo.BeamFieldVo;
import com.beamfield.modelVo.RoleModelTreeVo;
import com.beamfield.service.manage.auth.AuthService;
import com.beamfield.service.manage.sys.BeamFieldService;
import com.google.gson.JsonObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author Zephyr
 * @Description:
 * @Date 2018/10/9
 */
@Controller
@RequestMapping(value = "/mb_api")
public class MbLoginController extends MbBaseController {

    private final AuthService authService;

    private final BeamFieldService beamFieldService;

    @Autowired
    public MbLoginController(AuthService authService, BeamFieldService beamFieldService){
        this.authService = authService;
        this.beamFieldService = beamFieldService;
    }

    /**
     * 获取菜单权限
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getMenu", method = RequestMethod.POST)
    public ApiResult getMenu(HttpServletRequest request){
        Long userId = super.getLogInfo(request).getUserId();
        List<RoleModelTreeVo> menu = authService.getAllMenu(userId, "2");
        return new ApiResult(menu);
    }

    /**
     * 登出
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/signOut", method = RequestMethod.POST)
    public ApiResult signOut(HttpServletRequest request){
        try{
            String token = super.getToken(request);
            if(StringUtils.isNotEmpty(token)){
                TokenManage.removeToken(token);
            }
            return new ApiResult();
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
        }
    }

    @RequestMapping(value = "/login")
    @ResponseBody
    public ApiResult login(HttpServletRequest request, HttpServletResponse response){
        JSONObject resultJsonObject = new JSONObject();
        try {
            JSONObject jsonObject = CommonUtils.getJsonObject(request);
            if (jsonObject == null) {
                return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
            }
            JSONObject body = jsonObject.getJSONObject("body");
            if (body == null) {
                return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
            }
            String loginName = body.getString("loginName");
            String password = body.getString("password");

            if (StringUtils.isEmpty(loginName) || StringUtils.isEmpty(password)) {
                return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
            }

            AdminInfo admin = authService.getAdminByLogin(loginName, null);
            if(admin==null){
                return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(),"账号密码错误");
            }else{
                if(!Objects.equals(CommonUtils.MD5(CommonUtils.MD5(password)+loginName),admin.getPwd_eight())){
                    return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(),"账号密码错误");
                }else{
                    String beamId = admin.getBeam_id();
                    List<String> beamIdList = Arrays.stream(beamId.split(",")).filter(StringUtils::isNotEmpty).collect(Collectors.toList());
                    if(beamIdList.size() == 1){
                        BeamField beamField = beamFieldService.getBeamFieldVoByBeamId(Long.parseLong(beamIdList.get(0)));
                        LogInfo logInfo = new LogInfo();
                        logInfo.setLoginName(loginName);
                        logInfo.setBeamId(beamField.getBeam_id());
                        logInfo.setRealName(admin.getReal_name());
                        logInfo.setBeamName(beamField.getName());
                        logInfo.setUserId(admin.getAdmin_id());
                        String token = TokenManage.createToken(logInfo);
                        resultJsonObject.put("token", token);
                        resultJsonObject.put("beamName", beamField.getName());
                    }else{
                        List<BeamFieldVo> beamFieldByBeamIdList = beamFieldService.getBeamFieldByBeamIdList(beamIdList);
                        LogInfo logInfo = new LogInfo();
                        logInfo.setLoginName(loginName);
                        logInfo.setRealName(admin.getReal_name());
                        logInfo.setUserId(admin.getAdmin_id());
                        String token = TokenManage.createToken(logInfo);
                        resultJsonObject.put("beamIdList", beamFieldByBeamIdList);
                        resultJsonObject.put("token", token);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
        }
        return new ApiResult(resultJsonObject);
    }

    /**
     * 登录后选择梁场
     * @return
     */
    @RequestMapping(value = "/chooseBeamField", method = RequestMethod.POST)
    @ResponseBody
    public ApiResult chooseBeamField(HttpServletRequest request){
        JSONObject jsonObject = super.getBody(request);
        String token = super.getToken(request);
        if(jsonObject == null){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
        }
        String beamId = jsonObject.getString("beamId");
        if(StringUtils.isEmpty(token) || StringUtils.isEmpty(beamId)){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
        }
        JSONObject resultJsonObject = new JSONObject();
        try{
            BeamField beamField = beamFieldService.getBeamFieldVoByBeamId(Long.parseLong(beamId));
            String beamFieldName = beamField.getName();
            LogInfo logInfo = TokenManage.get(token);
            logInfo.setBeamName(beamFieldName);
            logInfo.setBeamId(beamField.getBeam_id());
            TokenManage.put(token, logInfo);
            resultJsonObject.put("token", token);
            resultJsonObject.put("beamName", beamFieldName);
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
        }
        return new ApiResult(resultJsonObject);
    }

    /**
     * 获取人员梁场列表
     * @param request
     * @return
     */
    @RequestMapping(value = "/getBeamFileList", method = RequestMethod.POST)
    @ResponseBody
    public ApiResult getBeamFileList(HttpServletRequest request){
        Long userId = super.getUserId(request);
        Long beamId = super.getBeamId(request);
        try{
            List<BeamFieldVo> beamFileList = beamFieldService.getBeamFileList(userId, beamId);
            return new ApiResult(beamFileList);
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
        }
    }
}
